<!--
 * @Description: 结算单表单
 * @Author: py
 * @Date: 2024-12-19
-->
<script setup lang="ts" name="settlement-form">
import type { FormInstance } from 'element-plus'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { comfirmOrSettleApi, orderDetailsApi, subOrdersExportApi, useComfirmOrSettle, useVendorConfirm, vendorConfirmApi } from '@fl/api/charge-settle'
import FlUpload from '@fl/components/fl-upload.vue'
import { formatTime } from '@fl/utils'
import { isImgPath } from '@fl/utils/is'
import { useRouter } from 'vue-router'
import XEUtils from 'xe-utils'

// import { useDicts } from './hooks/use-dicts'

// const { getDictLabel } = useDicts()

const router = useRouter()

const { query } = useRoute()
const { formType, id } = query

const formRef = ref()
type VoucherItem = {
    name: string
    url: string
}
const initialForm = {
    commission: '',
    parkingFee: '',
    settlementTime: '',
    vendorName: '',
    operatorName: '城服集团',
    settlementName: '',
    settlementCode: '',
    totalAmount: '',
    platformServiceFee: '',
    actualSettlementAmount: undefined,
    settlementDate: '',
    settlementOrderDate: '',
    settlementStatus: 1,
    settleVoucher: [] as VoucherItem[],
    // stepRate: [],
    dueSettlementAmount: undefined,
    revenue: '',
}
const formValues = ref({ ...initialForm })
const rules = {
    settlementTime: [{ message: '请选择结算时间', required: true, trigger: 'change' }],
    actualSettlementAmount: [{ message: '请输入结算金额', required: true, trigger: 'blur' }],
    settleVoucher: [{ message: '请上传结算凭证', required: true, trigger: 'change' }],
}

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function formatDate({ cellValue }) {
    return formatTime(cellValue, 'yyyy-MM-dd')
}

// 金额格式化 - 千分位
function formatMoney({ cellValue }) {
    const formatedNum = XEUtils.commafy(Number(cellValue), { digits: 2 })
    return cellValue === null ? '' : `¥ ${formatedNum}`
}

// 表单配置
const detailsGridOptions = reactive<VxeGridProps>({
    border: 'inner',
    columns: [
        { field: 'settlementDate', formatter: formatDate, title: '结算日期', width: 110 },
        { field: 'stationName', minWidth: 190, title: '充电站名称' },
        { field: 'pileCount', title: '桩数量(台)', width: 100 },
        { field: 'vendorName', minWidth: 160, title: '合作商名称' },
        { field: 'orderCount', title: '订单数量', width: 100 },
        { field: 'orderTotalCharge', title: '订单总电量', width: 110 },
        { align: 'right', field: 'totalAmount', formatter: formatMoney, title: '实收总金额', width: 120 },
        { align: 'right', field: 'actualChargeFee', formatter: formatMoney, title: '实收电费', width: 120 },
        { align: 'right', field: 'actualServiceFee', formatter: formatMoney, title: '实收服务费', width: 120 },
        { align: 'right', field: 'platformServiceFee', formatter: formatMoney, title: '平台技术服务费', width: 135 },
        { align: 'right', field: 'parkingFee', formatter: formatMoney, title: '停车费申诉扣减费', width: 145 },
        { field: 'settlementRatio', formatter: ({ cellValue }) => `${cellValue}%`, title: '适用结算比例', width: 120 },
        { align: 'right', field: 'commission', formatter: formatMoney, title: '佣金', width: 120 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 90 },
    ],
    data: [],
    // headerCellClassName: 'table-header-cell',
    // headerRowClassName: 'bg-white',
    loading: false,
    maxHeight: 360,
    minHeight: 60,
    size: 'medium',
})

const isFormLoading = ref(false)
// 获取表单详情信息-回显
function getFormDetails() {
    isFormLoading.value = true
    orderDetailsApi(id).then((data) => {
        formValues.value = data
        if (formType === 'settle') {
            formValues.value.actualSettlementAmount = formValues.value.dueSettlementAmount
            formValues.value.settlementTime = formatTime(new Date(), 'yyyy-MM-dd')
        }

        if (data.settlementUrl && isImgPath(data.settlementUrl)) {
            const arrUrl = data.settlementUrl.split(',')
            formValues.value.settleVoucher = arrUrl.map((item) => {
                const fileName = item.substring(item.lastIndexOf('/') + 1)
                return {
                    name: fileName,
                    url: item,
                }
            })
        }
        else {
            formValues.value.settleVoucher = []
        }

        if (data.subOrderList) {
            tablePage.total = data.subOrderList.length
            detailsGridOptions.data = data.subOrderList
        }
    }).finally(() => {
        isFormLoading.value = false
    })
}

getFormDetails()

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    // getList()
}

function handleExport(row) {
    subOrdersExportApi({ id: row.id }).then((res) => {
        // downloadFileWithData
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    })
}

const { mutate } = useComfirmOrSettle()
const { mutate: vendorMutate } = useVendorConfirm()

function onSuccess(message) {
    ElMessage.success({
        duration: 2000,
        message,
    })

    setTimeout(() => {
        router.back()
    }, 2000)
}
// 提交表单
async function handleSubmit(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate(async (valid) => {
        if (valid) {
            // isFormLoading.value = true;
            try {
                if (formType === 'operatorConfirm') {
                    // await comfirmOrSettleApi({ id });
                    mutate({ id }, {
                        onSuccess: () => {
                            onSuccess('已确认')
                        },
                    })
                }
                else if (formType === 'vendorConfirm') {
                    // await vendorConfirmApi({ id });
                    vendorMutate({ id }, {
                        onSuccess: () => {
                            onSuccess('已确认')
                        },
                    })
                }
                else if (formType === 'settle') {
                    const {
                        actualSettlementAmount,
                        settlementTime,
                        settleVoucher,
                    } = formValues.value
                    const urlList = settleVoucher.map(uItem => uItem.url)
                    const oParams = {
                        id,
                        actualSettlementAmount,
                        settlementTime: `${settlementTime} 00:00:00`,
                        settlementUrl: urlList.join(','),
                    }
                    // await comfirmOrSettleApi(oParams);
                    mutate(oParams, {
                        onSuccess: () => {
                            onSuccess('结算成功')
                        },
                    })
                }

                // setTimeout(() => {
                //     router.back()
                // }, 2000)
            }
            catch (error) {
                console.error(error)
            }
            // finally {
            //     isFormLoading.value = false
            // }
        }
    })
}
</script>

<template>
    <el-skeleton v-if="isFormLoading"
                 :rows="8"
    />

    <div v-else
         class="form-panel"
    >
        <el-button class="mb-20"
                   @click="$router.back"
        >
            返回列表
        </el-button>

        <div class="form-content">
            <el-form ref="formRef"
                     :model="formValues"
                     :rules="rules"
                     require-asterisk-position="right"
                     label-width="auto"
                     class="mb-20"
            >
                <h2 class="module-title pl-24">
                    结算信息
                </h2>

                <div class="px-24">
                    <el-row :gutter="16"
                            class="px-16 pt-16 bg-#f7f8fa"
                    >
                        <el-col :span="4">
                            <el-form-item label="实收总金额"
                                          label-position="top"
                                          class="gapy-8"
                            >
                                <p class="text-money">
                                    ¥{{ formValues.totalAmount }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4">
                            <el-form-item label="平台技术服务费"
                                          label-position="top"
                                          class="gapy-8"
                            >
                                <p class="text-money">
                                    ¥{{ formValues.platformServiceFee }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4">
                            <el-form-item label="停车费申诉扣减费"
                                          label-position="top"
                                          class="gapy-8"
                            >
                                <p class="text-money">
                                    ¥{{ formValues.parkingFee }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4">
                            <el-form-item label-position="top"
                                          class="gapy-8"
                            >
                                <template #label>
                                    <div class="flex items-center">
                                        <span class="mr-4">营业额</span>

                                        <el-tooltip content="营业额 = 实收总金额 + 平台技术服务费 - 停车申诉扣减费"
                                                    :offset="8"
                                                    placement="top"
                                        >
                                            <vxe-icon name="question-circle"
                                                      class="cursor-pointer"
                                            />
                                        </el-tooltip>
                                    </div>
                                </template>

                                <p class="text-money">
                                    ¥{{ formValues.revenue }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4">
                            <el-form-item label-position="top"
                                          class="gapy-8"
                            >
                                <template #label>
                                    <div class="flex items-center">
                                        <span class="mr-4">佣金</span>

                                        <el-tooltip content="佣金 = 平台技术服务费 * 适用结算比例"
                                                    :offset="8"
                                                    placement="top"
                                        >
                                            <vxe-icon name="question-circle"
                                                      class="cursor-pointer"
                                            />
                                        </el-tooltip>
                                    </div>
                                </template>

                                <p class="text-money">
                                    ¥{{ formValues.commission }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="4">
                            <el-form-item label-position="top"
                                          class="gapy-8"
                            >
                                <template #label>
                                    <div class="flex items-center">
                                        <span class="mr-4">应结算金额</span>

                                        <el-tooltip content="应结算金额 = 营业额 - 平台技术服务费 - 佣金"
                                                    :offset="8"
                                                    placement="top"
                                        >
                                            <vxe-icon name="question-circle"
                                                      class="cursor-pointer"
                                            />
                                        </el-tooltip>
                                    </div>
                                </template>

                                <p class="text-money">
                                    ¥{{ formValues.dueSettlementAmount }}
                                </p>
                            </el-form-item>
                        </el-col>

                        <template v-if="formType === 'detail' && formValues.settlementStatus === 5">
                            <el-col :span="4">
                                <el-form-item label="实际结算金额(元)"
                                              label-position="top"
                                              class="gapy-8"
                                >
                                    <p class="text-money">
                                        ¥{{ formValues.actualSettlementAmount }}
                                    </p>
                                </el-form-item>
                            </el-col>

                            <el-col :span="4">
                                <el-form-item label="结算时间"
                                              label-position="top"
                                              class="gapy-8"
                                >
                                    <p class="text-money">
                                        {{ formValues.settlementTime }}
                                    </p>
                                </el-form-item>
                            </el-col>

                            <el-col :span="16">
                                <el-form-item label="结算凭证"
                                              label-position="top"
                                              class="gapy-8"
                                >
                                    <FlUpload v-model="formValues.settleVoucher"
                                              accept=".png,.jpg,.jpeg"
                                              :file-size="50"
                                              :limit="10"
                                              disabled
                                    />
                                </el-form-item>
                            </el-col>
                        </template>
                    </el-row>
                </div>

                <div class="module-divider" />

                <h2 class="module-title pl-24">
                    基本信息
                </h2>

                <el-row :gutter="16"
                        class="px-24"
                >
                    <el-col :span="8">
                        <el-form-item label="结算单号："
                                      class="form-item-display"
                        >
                            {{ formValues.settlementCode }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="结算单名称："
                                      class="form-item-display"
                        >
                            {{ formValues.settlementName }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="结算日期："
                                      class="form-item-display"
                        >
                            {{ formatTime(formValues.settlementDate, 'yyyy-MM-dd') }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="结算订单期间："
                                      class="form-item-display"
                        >
                            {{ formatTime(formValues.settlementOrderDate, 'yyyy-MM-dd') }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="运营商名称："
                                      class="form-item-display"
                        >
                            {{ formValues.operatorName }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="合作商名称："
                                      class="form-item-display"
                        >
                            {{ formValues.vendorName }}
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="module-divider" />

                <h2 class="module-title pl-24">
                    订单列表
                </h2>

                <div class="px-24">
                    <vxe-grid v-bind="detailsGridOptions">
                        <template #top>
                            <div class="row-total">
                                <span class="mr-24">全部：共{{ tablePage.total }}笔订单</span>

                                <span class="mr-24">实收总金额：<span class="text-#da0004">¥ {{ formValues.totalAmount }}</span></span>

                                <span class="mr-24">平台技术服务费：¥ {{ formValues.platformServiceFee }}</span>

                                <span class="mr-24">停车费申诉扣减费：¥ {{ formValues.parkingFee }}</span>
                            </div>
                        </template>

                        <template #operate="{ row }">
                            <div class="row-btns">
                                <span class="btn-operate"
                                      @click="handleExport(row)"
                                >
                                    导出明细
                                </span>
                            </div>
                        </template>

                        <template #pager>
                            <vxe-pager :current-page="tablePage.currentPage"
                                       :page-size="tablePage.pageSize"
                                       :total="tablePage.total"
                                       :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                                       background
                                       @page-change="handlePageChange"
                            />
                        </template>
                    </vxe-grid>
                </div>

                <template v-if="formType === 'settle'">
                    <div class="module-divider" />

                    <h2 class="module-title pl-24">
                        结算内容填写
                    </h2>

                    <el-row :gutter="16"
                            class="px-24"
                    >
                        <el-col :span="8">
                            <el-form-item label="实际结算金额(元)"
                                          label-position="top"
                                          prop="actualSettlementAmount"
                            >
                                <el-input-number v-model="formValues.actualSettlementAmount"
                                                 class="input-num"
                                                 :controls="false"
                                                 :min="0"
                                                 :precision="2"
                                                 placeholder="请输入"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="结算时间"
                                          label-position="top"
                                          prop="settlementTime"
                            >
                                <el-date-picker v-model="formValues.settlementTime"
                                                type="date"
                                                placeholder="请选择"
                                                value-format="YYYY-MM-DD"
                                                style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="结算凭证"
                                          label-position="top"
                                          prop="settleVoucher"
                            >
                                <FlUpload v-model="formValues.settleVoucher"
                                          accept=".png,.jpg,.jpeg"
                                          :file-size="50"
                                          :limit="10"
                                />

                                <p class="tips-upload">
                                    请上传 大小不超过 50MB，格式为 png/jpg/jpeg 的图片
                                </p>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
            </el-form>
        </div>

        <div v-if="formType === 'detail'"
             class="form-footer"
        >
            <el-button @click="$router.go(-1)">
                返回
            </el-button>
        </div>

        <div v-if="formType !== 'detail'"
             class="form-footer"
        >
            <el-button @click="$router.go(-1)">
                取消
            </el-button>

            <el-button type="primary"
                       @click="handleSubmit(formRef)"
            >
                提交
            </el-button>
        </div>
    </div>
</template>

<style lang="less" scoped>
@import '../custom.less';

.input-num {
    width: 100%;

    :deep(.el-input__inner) {
        text-align: left;
    }
}
</style>
